package com.xxchat.utils;

import com.xxchat.config.AppConfig;
import com.xxchat.entity.constants.SysConstants;
import com.xxchat.entity.enums.ResponseCodeEnum;
import com.xxchat.exception.BusinessException;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;

/**
 * @author Waicc
 */
@Component("fileUploadUtils")
public class FileUploadUtils {

    @Resource
    private AppConfig appConfig;

    public void handleAvatarFile(String fileName, MultipartFile file) {
        try {
            String baseFolder = appConfig.getProjectFolder() + SysConstants.FILE_FOLDER_PATH_FILE + SysConstants.FILE_FOLDER_PATH_AVATAR;
            File targetFileFolder = new File(baseFolder);
            if (!targetFileFolder.exists()) {
                if (!targetFileFolder.mkdirs()) {
                    throw new BusinessException(ResponseCodeEnum.CODE_500);
                }
            }
            String filePath = targetFileFolder.getPath() + File.separator + fileName;

            file.transferTo(new File(filePath));
        } catch (Exception e) {
            throw new BusinessException(ResponseCodeEnum.CODE_500);
        }
    }

    public void handleVersionFile(String fileName, MultipartFile file) {
        try {
            String baseFolder = appConfig.getProjectFolder() + SysConstants.FILE_FOLDER_PATH_FILE + SysConstants.FILE_FOLDER_PATH_VERSION;
            File targetFileFolder = new File(baseFolder);
            if (!targetFileFolder.exists()) {
                if (!targetFileFolder.mkdirs()) {
                    throw new BusinessException(ResponseCodeEnum.CODE_500);
                }
            }
            String filePath = targetFileFolder.getPath() + File.separator + fileName;

            file.transferTo(new File(filePath));
        } catch (Exception e) {
            throw new BusinessException(ResponseCodeEnum.CODE_500);
        }
    }
}
